﻿using UnityEngine;
using System.Collections;

public class ExitHint : MonoBehaviour {
	public GameObject hintObj;
	public Camera mainCamera;
	private float widthUnit, heightUnit;
	private ArrayList exitList;
	private ArrayList exitHintObjList;
	private bool firstFrame;
	// Use this for initialization
	void Start () {
		firstFrame = true;
		CalculateCameraFrame();
		exitList = GameObject.Find("GameMgr").GetComponent<GameManager>().exitList;
		//SpawnHintArrow();
	}
	
	// Update is called once per frame
	void Update () {
		if(firstFrame){
			SpawnHintArrow();
			firstFrame = false;
		}else{
			int i = 0;
			foreach(Exit e  in exitList){
				Vector3 ePos = e.position;
				Vector3 cPos = mainCamera.transform.position;
				GameObject eObj = exitHintObjList[i] as GameObject;
				if(!IsInsideScreen(ePos, cPos)){
					eObj.SetActive(true);
					eObj.transform.position = GetIntersection(ePos, cPos);
					Vector3 forward = new Vector3(ePos.x - cPos.x, ePos.y - cPos.y, 0);
					eObj.transform.rotation = Quaternion.LookRotation(forward, Vector3.back);
				}else{
					eObj.SetActive(false);
				}
				i++;
			}
		}

	}

	void CalculateCameraFrame(){
		int screenWidth = Screen.width;
		int screenHeight = Screen.height;
		int spriteToPixel = (int)(screenWidth / (mainCamera.aspect * 2 * mainCamera.orthographicSize));

		widthUnit = screenWidth / spriteToPixel / 2;
		heightUnit = screenHeight / spriteToPixel / 2;

		//Debug.Log(widthUnit + "," + heightUnit);
	}

	bool IsInsideScreen(Vector3 exitPos, Vector3 cameraPos){
		if((Mathf.Abs(exitPos.x - cameraPos.x) < widthUnit)
			&&(Mathf.Abs(exitPos.y - cameraPos.y) < heightUnit))
					return true;
		return false;
	}

	void SpawnHintArrow(){
		int arrowHintSize = exitList.Count;
		exitHintObjList = new ArrayList();
		for(int i = 0; i < arrowHintSize; i++){
			GameObject obj = Instantiate(hintObj, mainCamera.transform.position, Quaternion.identity) as GameObject;
			exitHintObjList.Add(obj);
		}
	}

	//assuming the exit is not inside of the screen
	Vector3 GetIntersection(Vector3 farPoint, Vector3 centerPoint){
		float xDiff = farPoint.x - centerPoint.x;
		float yDiff = farPoint.y - centerPoint.y;

		float ratio = xDiff / yDiff;
		Vector3 intersection;
		float t;
		if(Mathf.Abs(ratio) > mainCamera.aspect){ // width already known, want to know height
			t = widthUnit / Mathf.Abs(xDiff);
			intersection.x = xDiff > 0 ? centerPoint.x + widthUnit - 1 : centerPoint.x - widthUnit + 1;
			intersection.y = centerPoint.y + t * yDiff;
			intersection.y = yDiff > 0 ? intersection.y - 1 : intersection.y + 1;
		}else{ // height already know, want to know width
		 	t = heightUnit / Mathf.Abs(yDiff);
			intersection.y = yDiff > 0 ? centerPoint.x + heightUnit - 1 : centerPoint.y - heightUnit + 1;
			intersection.x = centerPoint.x + t * xDiff;
			intersection.x = xDiff > 0 ? intersection.x - 1 : intersection.x + 1;
		}
		intersection.z = mainCamera.transform.position.z + 1.0f;
		return intersection;
	}

}
